package com.sunnyweather.android.logic.service

import android.app.Service
import android.content.Intent
import android.os.IBinder
import android.os.Message
import com.sunnyweather.android.logic.Repository
import com.sunnyweather.android.logic.util.LogUtil
import com.sunnyweather.android.ui.weather.WeatherActivity
import kotlinx.coroutines.*

class RefreshWeatherService : Service() {


    override fun onBind(intent: Intent): IBinder {
        TODO("Return the communication channel to the service.")
    }

    override fun onCreate() {
        super.onCreate()
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {

        val job=Job()
        val scope= CoroutineScope(job)
        //借助协程开启子线程并运行后台任务。
        scope.launch(Dispatchers.IO) {
            //子线程内又会开启多个子线程去发起请求
            cycleTask()
        }
        return super.onStartCommand(intent, flags, startId)
    }

    override fun onDestroy() {
        super.onDestroy()
    }

    //后台执行的循环任务
    suspend fun cycleTask(){
        LogUtil.d("ServiceThread",Thread.currentThread().name)
        val result=Repository.updateAllWeather()
        if(result){
            //如果更新成功就发送广播通知Activity
            val intent=Intent("com.sunnyweather.android.UPDATE_WEATHER_UI")
            intent.setPackage(packageName)
            WeatherActivity.broadcastManager?.sendBroadcast(intent)
        }
        delay(1000*60*60)
        cycleTask()
    }
}